/*
 * line.c count how many line in a file
 * copyright August 2013
 * chrismas 2013 
 * written by phamthechung0@gmail.com
 * compile: cc line.c -o line -Iinclude getopt.o
 * all human were die,no body live
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <piece/getopt.h>
#include <piece/c_lang.h>
void die(char *s){
	puts(s);
	exit(0);
}
#define ALL	1
#define WOC	2 //count without comment
#define WON	3
size_t count_line(char *file,int mode){
	size_t line=0;
	int ch=0,rem=0,com=0;
	FILE *fp=fopen(file,"r");
	switch(mode){
		case ALL:
			while((ch=fgetc(fp))!=EOF){
				if(ch=='\n') line++;
			}
		break;
		case WOC:
			while((ch=fgetc(fp))!=EOF){
				if(ch=='/') rem=ch;
				if(ch=='*') rem=ch;
				if(ch=='*'&&rem=='/') com=1;
				if(ch=='/'&&rem=='*') com=0;
				if(ch=='\n'&&com==0) line++;
			}
		break;
	}
	fclose(fp);
	return line;
}
/*
	todo: how to dump file with line number appear before text line
	yes i do it already
*/
void print_file(char *file){
	int ch=0,line=1,sl=0,first=1;
	FILE *fp=fopen(file,"r");
	while((ch=fgetc(fp))!=EOF){
		if(first) {printf("%d  ",line++);first=0;}
		if(ch=='\n') sl=1;
		else sl=0;
		putchar(ch);
		if(sl==1) {printf("%d   ",line++);sl=0;}
	}
	fclose(fp);
}
char *version="line version 1.1\n\
Written by Pham The Chung\n\
email: phamthechung0@gmail.com\n";
char *help="usage: line [option] file1 file2 file3\n\
option:\n\
	p	print file with line number \n\
	n	count line but no comment\n\
	v	show version and exit\n\
	h	show help message and exit\n";
char *option="vhnp";
MAIN {
	char **vfile;
	vfile=argv+1;
	if(argc<2) die("line: no argument\n");
	else{
		if(!strcmp(argv[1],"--version"))
		{  puts(version); exit(0);}
		if(!strcmp(argv[1],"--help")) {puts(help);exit(0);}
	}
	int ch=0;
	char pf=0,nf=0;
	while((ch=getopt(argc,argv,option))!=NULL){
		switch(ch){
		  case 'p': pf=1;break;
		  case 'n': nf=1;break;
		  case 'v': puts(version);exit(0); break;
		  case 'h': puts(help);exit(0);break;
		  case '*': vfile=&argv[optfree];
					break;
		}
	}
	int r=0;
	size_t line=1;
	char status=0;
	while(vfile[r]){
	  if(nf) {line=count_line(vfile[r],WOC);status=1;}
	  if(pf==1) print_file(vfile[r]);
	  if(nf==0) {line =count_line(vfile[r],ALL);status=1;}
	  if(status) printf("%s %d\n",vfile[r],line);
	  line=0;
	  r++;
	}
}